using System.Web.UI;
using Quiki.ExpressionParsers;

namespace Quiki.ElementFormatters
{
    public class ImageElementFormatter : LambdaElementFormatter
    {
        public ImageElementFormatter(ImageDataParser imageDataParser)
            : base(WikiTextElementType.Image, null, null)
        {
            this.imageDataParser = imageDataParser;
            BeginAction = CustomBeginAction;
        }

        private void CustomBeginAction(WikiTextElement element, HtmlFormatterContext context)
        {
            WikiImageElement imageElement = (WikiImageElement)element;
            ImageData imageData = imageDataParser.Parse(imageElement);

            context.Writer.AddAttribute(HtmlTextWriterAttribute.Class, "image");
            context.Writer.RenderBeginTag(HtmlTextWriterTag.Div);

            string url = context.Document.PathToRoot + "images/" + imageElement.Name;

            context.Writer.AddAttribute(HtmlTextWriterAttribute.Src, url);

            if (false == string.IsNullOrEmpty(imageData.Width))
                context.Writer.AddAttribute(HtmlTextWriterAttribute.Width, imageData.Width);

            context.Writer.RenderBeginTag(HtmlTextWriterTag.Img);
            context.Writer.RenderEndTag();

            context.Writer.RenderEndTag();
        }

        private readonly ImageDataParser imageDataParser;
    }
}